package io.zcoder.innoway.activities;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.crashlytics.android.Crashlytics;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.DataUser;
import io.zcoder.innoway.models.Profile;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.models.User;
import io.zcoder.innoway.models.UserResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.EditTextCustom;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class BasicInformationActivity extends BaseActivity {

    @BindView(R.id.next)
    TextViewCustom mNext;
    @BindView(R.id.first_name)
    EditTextCustom mFirstName;
    @BindView(R.id.last_name)
    EditTextCustom mLastName;
    @BindView(R.id.email)
    EditTextCustom mEmail;
    @BindView(R.id.pass_1)
    EditTextCustom mPass1;
    @BindView(R.id.pass_2)
    EditTextCustom mPass2;

    @OnClick(R.id.next)
    void onDone() {
        validate();
    }

    private void validate() {
        if (mFirstName.isEmpty() || mLastName.isEmpty() || mEmail.isEmpty() || mPass1.isEmpty() || mPass2.isEmpty()) {
            showAlert(getString(R.string.error), getString(R.string.error_empty));
            return;
        }
        if (!mPass1.getText().toString().equalsIgnoreCase(mPass2.getText().toString()) || mPass1.getText().length() < 6) {
            showAlert(getString(R.string.error), getString(R.string.error_pass));
            return;
        }
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(mEmail.getText()).matches()) {
            showAlert(getString(R.string.error), getString(R.string.error_email));
            return;
        }
        mUser = new User();
        mUser.setProfile(mProfile);
        mUser.setFirst_name(mFirstName.getText().toString());
        mUser.setLast_name(mLastName.getText().toString());
        mUser.setEmail(mEmail.getText().toString());
        mUser.setPassword(mPass1.getText().toString());
        createProfile();
    }

    private void createProfile() {
        showProgress();
        RestClient.build(this, false).createUser(mUser,
                new Callback<UserResponse>() {
                    @Override
                    public void success(UserResponse userResponse, Response response) {
                        if (userResponse.getStatus_code() != 200) {
                            showAlert(getString(R.string.error), userResponse.getMessage());
                        } else if (userResponse.getData() != null) {
                            saveUserInfo(userResponse.getData());
                        }
                        hideProgress();
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        hideProgress();
                    }
                });
    }

    private void saveUserInfo(DataUser data) {
        PrefUtils.setString(BasicInformationActivity.this, PrefUtils.PREF_AUTHEN_TOKEN, data.getAuth_token());
        if (data.getProfiles() != null && !data.getProfiles().isEmpty()) {
            PrefUtils.setInt(BasicInformationActivity.this, PrefUtils.PREF_USER_ID, data.getProfiles().get(0).getUser_id());
            PrefUtils.setInt(BasicInformationActivity.this, PrefUtils.PREF_PROFILE_ID, data.getProfiles().get(0).getId());
            mProfile.setId(data.getProfiles().get(0).getId());
            RestClient.build(this, true).saveEditInfo(PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID),
                    mProfile.getHeight(), mProfile.getHeight_unit(), mProfile.getBirthday(), mFirstName.getText().toString(), mLastName.getText().toString(), mProfile.getInitWeight(), new Callback<ResponseBase>() {
                        @Override
                        public void success(ResponseBase responseBase, Response response) {
                            hideProgress();
                            if (responseBase.getStatus_code() != 200) {
                                showAlert(getString(R.string.error), responseBase.getMessage());
                            } else {
                                Intent intent = new Intent(BasicInformationActivity.this, TopActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            hideProgress();
                        }
                    });

        }
        logUser(data);
    }

    private void logUser(DataUser data) {
        // You can call any combination of these three methods
        Crashlytics.setUserIdentifier(data.getId() +"");
        Crashlytics.setUserEmail(data.getEmail());
        Crashlytics.setUserName(data.getProfiles().get(0).getFirst_name() + " " + data.getProfiles().get(0).getLast_name());
    }

    private User mUser;
    private Profile mProfile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_basic_information_activity);
        ButterKnife.bind(this);
        showBack(true);
        mProfile = getIntent().getParcelableExtra(Constants.PROFILE_EXTRAS);
        mNext.setText(getString(R.string.done));
    }
}
